{% extends "layout-settings.html" %}
{% set active_page = "settings" %}
{% set active_settings = "users" %}
{% set help_page = ["https://kizniche.github.io/Mycodo/Configuration-Settings/#users", dict_translation['settings']['title'] + ': ' + dict_translation['user']['title']] %}

{% block title %} - {{dict_translation['settings']['title'] + ': ' + dict_translation['user']['title']}}{% endblock %}

{% block head %}
<link href="/static/css/toastr.min.css" rel="stylesheet"/>
<script src="/static/js/toastr.min.js"></script>

<script>
  $(document).ready(function () {
    toastr.options = {
      "closeButton": true,
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-left",
      "preventDuplicates": false,
      "onclick": null,
      "showDuration": "300",
      "hideDuration": "1000",
      "timeOut": "15000",
      "extendedTimeOut": "10000",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut"
    }

    $('form').submit(function (e) {
      let submitter_btn = $(e.originalEvent.submitter);

      if (submitter_btn.attr("name") === 'settings_user_save' ||
          submitter_btn.attr("name") === 'user_generate_api_key' ||
          submitter_btn.attr("name") === 'user_delete' ||
          submitter_btn.attr("name") === 'user_save' ||
          submitter_btn.attr("name") === 'user_role_save' ||
          submitter_btn.attr("name") === 'user_role_delete') {
        {% if not misc.hide_alert_info %}toastr['info']('Command sent. Please wait...');{% endif %}
        $.ajax({
          type: "POST",
          url: '/settings/users_submit',
          data: $(this).serialize()
              + '&'
              + submitter_btn.attr("name")
              + '='
              + submitter_btn.attr("value"),
          success: function (data) {
            if (data.data.messages.error.length === 0) {
              if ('logout' in data.data && data.data.logout) {
                window.location.href = "/logout";
              }
              if (submitter_btn.attr("name") === 'user_generate_api_key' && 'generated_api_key' in data.data) {
                document.forms['user_' + data.data.user_id]['api_key'].value = data.data.generated_api_key;
              }
              if (submitter_btn.attr("name") === 'user_delete' && 'user_id' in data.data) {
                $('#user_' + data.data.user_id).hide('slow');
                $('#user_spacer_' + data.data.user_id).hide('slow');
              }
              if (submitter_btn.attr("name") === 'user_role_delete' && 'role_id' in data.data) {
                $('#role_' + data.data.role_id).hide('slow');
                $('#role_spacer_' + data.data.role_id).hide('slow');
              }
              {% if not misc.hide_alert_warning %}
              if ('warning' in data.data.messages && data.data.messages.warning.length !== 0) {
                toastr['warning']('Warning: ' + data.data.messages.warning.join(", "));
              }
              {% endif %}
              {% if not misc.hide_alert_info %}
              if ('info' in data.data.messages && data.data.messages.info.length !== 0) {
                toastr['info']('Info: ' + data.data.messages.info.join(", "));
              }
              {% endif %}
              {% if not misc.hide_alert_success %}
              if ('success' in data.data.messages && data.data.messages.success.length !== 0) {
                toastr['success']('Success: ' + data.data.messages.success.join(", "));
              }
              {% endif %}
            } else {
              toastr['error']('Error: ' + data.data.messages.error.join(", "));
            }
          },
          error: function() {
            toastr['error']('Error: Could not communicate with server');
          }
        });
        e.preventDefault();
      }
    });

    $.ajaxSetup({
      beforeSend: function (xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", "{{form_user.csrf_token._value()}}")
        }
      }
    })
  });
</script>
{% endblock %}

{% block settings %}
  <!-- Route: /settings/users -->
  <div class="container">
    <h3 style="text-align: right; padding-bottom: 1.3em;"><a href="https://kizniche.github.io/Mycodo/Configuration-Settings/#users" target="_blank"><span style="font-size: 16px" class="fas fa-question-circle"></span></a> {{_('User Settings')}}</h3>

    <form class="form-horizontal" method="post" action="/settings/users">
      {{form_user.csrf_token}}
      <div class="row align-items-end small-gutters">

        <div class="col-auto">
          {{form_user.default_login_page.label(class_='control-label')}}
          <div>
            <select class="form-control form-tooltip form-dropdown" data-placement="top" id="default_login_page" name="default_login_page" title="{{_('Which page to land on before logging in')}}">
              <option value="password"{% if misc.default_login_page == 'password' %} selected{% endif %}>{{_('Password')}}</option>
              <option value="keypad"{% if misc.default_login_page == 'keypad' %} selected{% endif %}>{{_('Keypad')}}</option>
            </select>
          </div>
        </div>
        <div class="col-12" style="padding-top: 1em">
          {{form_user.settings_user_save(class_='btn btn-primary')}}
        </div>
      </div>
    </form>

    <div style="clear: both; padding: 1em 0;"></div>

    <h3>{{_('Add User')}}</h3>

    <p>Note: If used, the Keypad Code must be a numerical value of 4 or more digits.</p>

    <form class="form-horizontal" method="post" action="/settings/users">
    {{form_add_user.hidden_tag()}}

    <div class="row align-items-end small-gutters">

      <div class="col-6 col-sm-3 col-md-3">
        {{form_add_user.user_name.label(class_='control-label')}}
        <div>
          {{form_add_user.user_name(class_='form-control')}}
        </div>
      </div>
      <div class="col-6 col-sm-3 col-md-3">
        {{form_add_user.email.label(class_='control-label')}}
        <div>
          {{form_add_user.email(class_='form-control')}}
        </div>
      </div>
      <div class="col-6 col-sm-3 col-md-3">
        {{form_add_user.password_new.label(class_='control-label')}}
        <div>
          {{form_add_user.password_new(class_='form-control')}}
        </div>
      </div>
      <div class="col-6 col-sm-3 col-md-3">
        {{form_add_user.password_repeat.label(class_='control-label')}}
        <div>
          {{form_add_user.password_repeat(class_='form-control')}}
        </div>
      </div>
      <div class="col-sm-3 col-md-3">
        {{form_add_user.code.label(class_='control-label')}}
        <div>
          {{form_add_user.code(class_='form-control')}}
        </div>
      </div>
      <div class="col-4 col-sm-3 col-md-3">
        {{form_add_user.addRole.label(class_='control-label')}}
        <div>
          <select class="form-control" id="addRole" name="addRole">
            <option value="Admin">Admin</option>
            {% for each_role in user_roles if each_role.name != 'Admin' %}
              <option value="{{each_role.name}}">{{each_role.name}}</option>
            {% endfor -%}
          </select>
        </div>
      </div>
      <div class="col-4 col-sm-3 col-md-3">
      {{form_add_user.theme.label(class_='control-label')}}
        <div>
          <select class="form-control" id="theme" name="theme">
            {% for value, name in themes %}
              <option value="{{value|e}}"{% if value == 'spacelab' %} selected{% endif %}>{{name|e}}</option>
            {% endfor -%}
          </select>
        </div>
      </div>
      <div class="col-4 col-sm-3 col-md-3">
        {{form_add_user.user_add(class_='btn btn-primary')}}
      </div>
    </div>

    </form>

    <div style="clear: both; padding: 1em 0;"></div>

    <h3>{{_('Users')}}</h3>

    <p>Note: The Password and Keypad Code fields used to log in will remain empty. To change the password or code, enter a value and press save. Leaving them empty will keep the current setting. To disable a Keypad Code, enter 0 and save.</p>

    {% for user in users %}

    <form method="post" id="user_{{user.unique_id}}" action="/settings/users">
      {{form_mod_user.csrf_token}}
      {{form_mod_user.user_id(value=user.unique_id)}}
      <h6>User: {{user.name}}, Keypad Code Set: {% if user.code %}True{% else %}False{% endif %}</h6>

      <div class="row small-gutters">
        <div class="col-sm-6 col-md-3">
          {{form_mod_user.email(class_='form-control', value=user.email)}}
        </div>
        <div class="col-sm-3 col-md-3">
          {{form_mod_user.password_new(class_='form-control')}}
        </div>
        <div class="col-sm-3 col-md-3">
          {{form_mod_user.password_repeat(class_='form-control')}}
        </div>
        <div class="col-sm-3 col-md-3">
          {{form_mod_user.code(class_='form-control')}}
        </div>
        <div class="col-sm-3">
          <select class="form-control" id="role_id" name="role_id">
            {% for each_role in user_roles %}
              <option value="{{each_role.id}}"{% if user.role_id == each_role.id %} selected{% endif %}>{{each_role.name}}</option>
            {% endfor %}
          </select>
        </div>
        <div class="col-sm-3">
          <select class="form-control" id="theme" name="theme">
            {% for value, name in themes %}
              <option value="{{value|e}}"{% if value == user.theme %} selected{% endif %}>{{name|e}}</option>
            {% endfor -%}
          </select>
        </div>
        <div class="col-6 col-sm-3 col-md-3">
          {% if user.api_key %}
            {{form_mod_user.api_key(class_='form-control', value=base64_encode_bytes(user.api_key), **{'title': 'API Key (Base64)'})}}
          {% else %}
            {{form_mod_user.api_key(class_='form-control', **{'title': 'API Key (Base64)'})}}
          {% endif %}
        </div>
        <div class="col-sm-6 col-md-3 small-gutters">
          {{form_mod_user.user_generate_api_key(class_='btn btn-primary btn-block')}}
        </div>
        <div class="col-sm-6 col-md-3 small-gutters">
          {{form_mod_user.user_save(class_='btn btn-primary btn-block')}}
        </div>
        <div class="col-sm-6 col-md-3 small-gutters">
          {{form_mod_user.user_delete(class_='btn btn-primary btn-block', **{'onclick':'return confirm("Are you sure you want to delete this?")'})}}
        </div>
      </div>

    </form>

    <div id="user_spacer_{{user.unique_id}}" style="clear: both; padding: 0.5em 0;"></div>

    {% endfor -%}

    <hr>

    <h3>{{_('Roles')}} <a href="https://kizniche.github.io/Mycodo/Configuration-Settings/#roles"><span style="font-size: 16px" class="fas fa-question-circle"></span></a></h3>

    <form method="post" action="/settings/users">
    {{form_user_roles.csrf_token}}

    <div class="row align-items-end small-gutters">
      <div class="col-auto">
        {{form_user_roles.name.label(class_='control-label')}}
        <div>
          {{form_user_roles.name(class_='form-control')}}
        </div>
      </div>
      <div class="col-auto">
        {{form_user_roles.user_role_add(class_='btn btn-primary')}}
      </div>
    </div>

    <div class="form-inline">
      <div class="form-check form-check-inline">
        {{form_user_roles.view_logs(class_='form-control')}}
        <label>{{form_user_roles.view_logs.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.view_stats(class_='form-control')}}
        <label>{{form_user_roles.view_stats.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.view_camera(class_='form-control')}}
        <label>{{form_user_roles.view_camera.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.view_settings(class_='form-control')}}
        <label>{{form_user_roles.view_settings.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.edit_users(class_='form-control')}}
        <label>{{form_user_roles.edit_users.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.edit_controllers(class_='form-control')}}
        <label>{{form_user_roles.edit_controllers.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.edit_settings(class_='form-control')}}
        <label>{{form_user_roles.edit_settings.label.text}}</label>
      </div>
      <div class="form-check form-check-inline">
        {{form_user_roles.reset_password(class_='form-control')}}
        <label>{{form_user_roles.reset_password.label.text}}</label>
      </div>
    </div>

    </form>

    {% if user_roles|length > 4 %}

      <div style="clear: both; padding: 1em 0;"></div>

      {% for each_role in user_roles if each_role.id > 1 %}

      <form method="post" id="role_{{each_role.unique_id}}" action="/settings/users">
        {{form_user_roles.csrf_token}}
        {{form_user_roles.role_id(value=each_role.unique_id)}}

        <div class="row small-gutters">
          <div class="col-auto">
            <input class="btn btn-primary" disabled="" value="{{each_role.name}}" type="text">
          </div>
          <div class="col-auto">
            {{form_user_roles.user_role_save(class_='btn btn-primary')}}
          </div>
          <div class="col-auto">
            {{form_user_roles.user_role_delete(class_='btn btn-primary', **{'onclick':'return confirm("Are you sure you want to delete this?")'})}}
          </div>
        </div>

        <div class="form-inline">
          <div class="form-check form-check-inline">
            {%- if each_role.view_logs == true -%}
              {{form_user_roles.view_logs(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.view_logs(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.view_logs.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.view_stats == true -%}
              {{form_user_roles.view_stats(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.view_stats(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.view_stats.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.view_camera == true -%}
              {{form_user_roles.view_camera(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.view_camera(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.view_camera.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.view_settings == true -%}
              {{form_user_roles.view_settings(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.view_settings(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.view_settings.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.edit_users == true -%}
              {{form_user_roles.edit_users(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.edit_users(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.edit_users.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.edit_controllers == true -%}
              {{form_user_roles.edit_controllers(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.edit_controllers(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.edit_controllers.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.edit_settings == true -%}
              {{form_user_roles.edit_settings(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.edit_settings(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.edit_settings.label.text}}</label>
          </div>
          <div class="form-check form-check-inline">
            {%- if each_role.reset_password == true -%}
              {{form_user_roles.reset_password(class_='form-control', checked=True)}}
            {%- else -%}
              {{form_user_roles.reset_password(class_='form-control')}}
            {%- endif %}
            <label>{{form_user_roles.reset_password.label.text}}</label>
          </div>
        </div>

        </form>

        <div id="roley_spacer_{{each_role.unique_id}}" style="clear: both; padding: 0.5em 0;"></div>

      {% endfor %}

    {% endif %}

  </div>

{% endblock %}
